/* eslint-disable jsx-a11y/label-has-associated-control */
import { useCallback, useEffect, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { isEmpty, Tabs, class_esy, isArray, Button } from 'esy-ui';
import { Empty, Header, Img } from '@/components';
import { postCreateOrder, postRechargeConfig } from '@/services';
import { useGlobalStore, useUserInfoStore } from '@/mobx';
import sltPng from '@/assets/images/common/deposit_check.png';
// import { deposit_input_cn } from '@/styles/esy-ui';
import { useFormatText, useNavigation } from '@/hooks';
import firePng from '@/assets/images/common/tag_fire.png';

const list = [
  {
    paneKey: 1,
    title: '在线充值',
    Describe: '在线充值',
    TitleImage: '',
    DescribeImage: '',
    AcTitleImage: '',
    AcDescribeImage: '',
    Pwtype: 0,
    contentData: [
      {
        Id: 1,
        MtypeId: 1,
        Title: '支付宝',
        Describe: '',
        TitleImage: 'https://cdn4.cldfvn.com/tpl/bankapply/BBALIPCN1.png?v=962276',
        DescribeImage: '',
        AcTitleImage: '',
        AcDescribeImage: '',
        ChannelList: [
          {
            IsHot: true,
            IsExclusive: false,
            IsFresh: false,
            IsRecommend: true,
            ModeId: 1,
            Pwtype: 1,
            ModeName: '小额UID',
            IconUrl: '',
            PayImage: '',
            HelpAddress: '',
            HelpDescribe: '',
            MinAmount: 0,
            MaxAmount: 0,
            AmountLimitType: 1,
            AmountLimitFix: '["100","200","500"]',
          },
          {
            IsHot: false,
            IsExclusive: false,
            IsFresh: false,
            IsRecommend: false,
            ModeId: 2,
            Pwtype: 1,
            ModeName: '中额UID',
            IconUrl: '',
            PayImage: '',
            HelpAddress: '',
            HelpDescribe: '',
            MinAmount: 500,
            MaxAmount: 2000,
            AmountLimitType: 2,
            AmountLimitFix: '',
          },
          {
            IsHot: false,
            IsExclusive: false,
            IsFresh: false,
            IsRecommend: false,
            ModeId: 3,
            Pwtype: 1,
            ModeName: '大额UID',
            IconUrl: '',
            PayImage: '',
            HelpAddress: '',
            HelpDescribe: '',
            MinAmount: 1000,
            MaxAmount: 10000,
            AmountLimitType: 2,
            AmountLimitFix: '',
          },
          {
            IsHot: false,
            IsExclusive: false,
            IsFresh: false,
            IsRecommend: false,
            ModeId: 4,
            Pwtype: 1,
            ModeName: '超大额UID',
            IconUrl: '',
            PayImage: '',
            HelpAddress: '',
            HelpDescribe: '',
            MinAmount: 2000,
            MaxAmount: 20000,
            AmountLimitType: 2,
            AmountLimitFix: '',
          },
        ],
      },
      {
        Id: 2,
        MtypeId: 1,
        Title: '微信',
        Describe: '',
        TitleImage: 'https://cdn4.cldfvn.com/tpl/bankapply/BBWECPCN1.png?v=962276',
        DescribeImage: '',
        AcTitleImage: '',
        AcDescribeImage: '',
        ChannelList: [
          {
            IsHot: false,
            IsExclusive: false,
            IsFresh: false,
            IsRecommend: false,
            ModeId: 5,
            Pwtype: 2,
            ModeName: '红包二维码',
            IconUrl: '',
            PayImage: '',
            HelpAddress: '',
            HelpDescribe: '',
            MinAmount: 200,
            MaxAmount: 5000,
            AmountLimitType: 2,
            AmountLimitFix: '',
          },
          {
            IsHot: false,
            IsExclusive: false,
            IsFresh: false,
            IsRecommend: false,
            ModeId: 6,
            Pwtype: 2,
            ModeName: 'IOS专属',
            IconUrl: '',
            PayImage: '',
            HelpAddress: '',
            HelpDescribe: '',
            MinAmount: 100,
            MaxAmount: 500,
            AmountLimitType: 2,
            AmountLimitFix: '',
          },
        ],
      },
      {
        Id: 3,
        MtypeId: 1,
        Title: '数字人名币',
        Describe: '',
        TitleImage: 'https://cdn4.cldfvn.com/tpl/bankapply/BBECNYCN1.png?v=962276',
        DescribeImage: '',
        AcTitleImage: '',
        AcDescribeImage: '',
        ChannelList: [
          {
            IsHot: false,
            IsExclusive: false,
            IsFresh: false,
            IsRecommend: false,
            ModeId: 7,
            Pwtype: 3,
            ModeName: '手机支付',
            IconUrl: '',
            PayImage: '',
            HelpAddress: '',
            HelpDescribe: '',
            MinAmount: 100,
            MaxAmount: 5000,
            AmountLimitType: 2,
            AmountLimitFix: '',
          },
          {
            IsHot: false,
            IsExclusive: false,
            IsFresh: false,
            IsRecommend: false,
            ModeId: 8,
            Pwtype: 3,
            ModeName: '利仁-634',
            IconUrl: '',
            PayImage: '',
            HelpAddress: '',
            HelpDescribe: '',
            MinAmount: 100,
            MaxAmount: 2000,
            AmountLimitType: 2,
            AmountLimitFix: '',
          },
        ],
      },
      {
        Id: 4,
        MtypeId: 1,
        Title: '抖音',
        Describe: '',
        TitleImage: 'https://cdn4.cldfvn.com/tpl/bankapply/BBTTCN1.png?v=962276',
        DescribeImage: '',
        AcTitleImage: '',
        AcDescribeImage: '',
        ChannelList: [
          {
            IsHot: false,
            IsExclusive: false,
            IsFresh: false,
            IsRecommend: false,
            ModeId: 9,
            Pwtype: 4,
            ModeName: '抖音',
            IconUrl: '',
            PayImage: '',
            HelpAddress: '',
            HelpDescribe: '',
            MinAmount: 200,
            MaxAmount: 2000,
            AmountLimitType: 2,
            AmountLimitFix: '',
          },
        ],
      },
      {
        Id: 5,
        MtypeId: 1,
        Title: '抖音1',
        Describe: '',
        TitleImage: 'https://cdn4.cldfvn.com/tpl/bankapply/BBTTCN1.png?v=962276',
        DescribeImage: '',
        AcTitleImage: '',
        AcDescribeImage: '',
        ChannelList: [
          {
            IsHot: false,
            IsExclusive: false,
            IsFresh: false,
            IsRecommend: false,
            ModeId: 9,
            Pwtype: 4,
            ModeName: '抖音',
            IconUrl: '',
            PayImage: '',
            HelpAddress: '',
            HelpDescribe: '',
            MinAmount: 200,
            MaxAmount: 2000,
            AmountLimitType: 2,
            AmountLimitFix: '',
          },
        ],
      },
    ],
  },
];

function RenderTitle(props: any) {
  const { title, isActive } = props;
  return <div className={class_esy(['text-sm font-bold', isActive ? 'text-color-21' : 'text-color-17'])}>{title}</div>;
}

// 当个选择
function RenderItem(props: any) {
  const { Id, checkId, change, TitleImage, Title, ModeName, isThree, ModeId, MinAmount, MaxAmount, IsRecommend, IsHot, text, AmountLimitType, AmountLimitFix } = props;
  let id;
  let title;
  let rangeAmont = '';
  // 三级通道的处理
  if (isThree) {
    // 唯一标识
    id = ModeId;
    // 名称显示
    title = ModeName;
    // 限额处理
    if (AmountLimitType === 1) {
      const btns = AmountLimitFix ? JSON.parse(AmountLimitFix) : null;
      rangeAmont = isArray(btns) ? `${btns[0]}${text('text_52')}~${btns[btns.length - 1]}${text('text_52')}` : '';
    } else {
      rangeAmont = `${MinAmount}
            ${text('text_52')}~${MaxAmount}
            ${text('text_52')}`;
    }
  } else {
    id = Id;
    title = Title;
  }

  return (
    <div className={class_esy([isThree ? 'inline-block' : 'w-1/4'])}>
      <div
        className={class_esy([
          'relative flex flex-col items-center justify-center box-border mx-1 mb-2 p-2 border border-solid rounded cursor-pointer text-xs',
          id === checkId ? 'border-color-21 shadow-sld' : 'border-color-19',
        ])}
        onClick={() => {
          change(id);
        }}
      >
        {isThree && IsRecommend ? (
          <div className='absolute -top-2.5 px-1 -left-1.5 font-bold bg-lg-5 rounded-r-3xl rounded-tl-3xl text-white flex items-center h-5 scale-75'>
            {IsHot ? <Img boxClassName='w-4 h-5' src={firePng} /> : null}
            {text('text_53')}
          </div>
        ) : null}
        {id === checkId ? <Img boxClassName='absolute right-0 top-0 w-4 h-4' src={sltPng} /> : null}
        {isThree ? null : <Img boxClassName='w-7 h-7 mb-2' src={TitleImage} />}
        <div>{title}</div>
        {isThree ? <div className='text-split mt-1 min-h-4'>{rangeAmont}</div> : null}
      </div>
    </div>
  );
}

function RenderContent(props: any) {
  const { data, Token } = props;
  const { text } = useFormatText();
  const navigation = useNavigation();
  const { changeState } = useGlobalStore();
  const [checkId, setCheckId] = useState(data[0]?.Id);
  const [cId, setCId] = useState<number>();
  const [value, setValue] = useState<string>('');

  useEffect(() => {
    if (isArray(data) && !isEmpty(data)) {
      const list = data.find((it) => it.Id === checkId)?.ChannelList || [];
      setCId(list[0]?.ModeId);
    }
  }, [checkId, data]);

  // 切换二级列表
  const change = useCallback((id: number) => {
    setCheckId(id);
    setValue('');
  }, []);

  // 切换通道
  const changeThree = useCallback((id: number) => {
    setCId(id);
    setValue('');
  }, []);

  if (isEmpty(data) || !isArray(data)) return <Empty />;

  // 三级通道
  const channels = data.find((its) => its.Id === checkId)?.ChannelList;

  // 当前的通道单个数据
  const channel = channels.find((it) => it.ModeId === cId);

  // 固定金额的按钮组合
  const btns = channel?.AmountLimitFix && channel?.AmountLimitType === 1 ? JSON.parse(channel?.AmountLimitFix) : null;

  // 充值
  const onDeposit = () => {
    if (Token && channel?.ModeId && Number(value) > 0) {
      changeState('isLoading', true);
      postCreateOrder({ ModeID: channel.ModeId, Amount: Number(value) })
        .then((res: any) => {
          // Toast.show({ content: text('text_50') });
          navigation(res?.Data);
        })
        .catch(() => {
          // Toast.show({ content: text('text_51') });
        })
        .finally(() => {
          changeState('isLoading', false);
        });
    }
  };

  return (
    <div className='overflow-y-auto h-full flex flex-col'>
      <div className='flex flex-wrap p-2.5 bg-white'>
        {data.map((it: any, i) => (
          <RenderItem key={it.Id || i} {...it} change={change} checkId={checkId} text={text} />
        ))}
      </div>
      <div className='flex flex-wrap mt-2.5 bg-white p-2.5'>
        {isArray(channels) ? channels.map((item, idx) => <RenderItem key={item.ModeId || idx} {...item} change={changeThree} isThree checkId={cId} text={text} />) : <Empty />}
      </div>
      <div className='bg-white flex-1 pt-6 pb-2.5 px-3'>
        <input
          className='border border-solid border-bdr-1 outline-none rounded px-2.5 py-1 text-sm placeholder:text-sm w-full focus:border-color-21 focus:shadow-sld'
          autoComplete='off'
          readOnly={channel?.AmountLimitType === 1}
          value={value}
          onChange={(e) => {
            const v = e?.target?.value || '';
            if (channel?.MaxAmount && v >= channel?.MaxAmount) {
              setValue(channel?.MaxAmount);
            } else {
              setValue(v);
            }
          }}
          onBlur={() => {
            // 极值控制
            if (channel?.MaxAmount && value > channel?.MaxAmount) {
              setValue(channel?.MaxAmount);
            } else if (channel?.MinAmount && value < channel?.MinAmount) {
              setValue(channel?.MinAmount);
            }
          }}
          placeholder={channel?.AmountLimitType === 1 ? text('text_47') : `${text('text_46')}${channel?.MinAmount}${text('text_52')}~${channel?.MaxAmount}${text('text_52')}`}
        />
        {isArray(btns) && !isEmpty(btns) ? (
          <div className='flex items-center gap-2 my-3 text-xs'>
            {btns.map((txt) => (
              <div
                key={txt}
                className={class_esy(['py-1 px-3 rounded cursor-pointer', value === txt ? 'bg-color-21 text-white' : 'bg-body'])}
                onClick={() => {
                  setValue(txt);
                }}
              >
                {txt}
              </div>
            ))}
          </div>
        ) : null}
        <div className='px-3 w-full box-border fixed z-10 bottom-4 left-0'>
          <div className='text-error text-xs font-bold py-4'>{text('text_48')}</div>
          <Button type={!value ? 'disabled' : 'default'} className='rounded' onClick={onDeposit}>
            {text('text_49')}
          </Button>
        </div>
      </div>
    </div>
  );
}

function Deposit() {
  const [data, setData] = useState([]);
  const { userInfo } = useUserInfoStore();
  const { changeState } = useGlobalStore();

  useEffect(() => {
    if (userInfo?.Token) {
      changeState('isLoading', true);
      postRechargeConfig({})
        .then((res: any) => {
          if (isArray(res?.Data)) {
            setData(res.Data.map((it) => ({ title: it.Title, paneKey: it.Id, contentData: it.SubList })));
          }
        })
        .catch(() => {
          setData(list);
        })
        .finally(() => {
          changeState('isLoading', false);
        });
    }
  }, [changeState, userInfo?.Token]);

  return (
    <div className='bg-body-2 h-full flex flex-col'>
      <Header title='text_4' isGoHome />
      {isEmpty(data) ? (
        <Empty />
      ) : (
        <Tabs
          classNames={{ titles: 'relative text-base flex-nowrap bg-white', indicator: 'absolute bg-color-21 rounded-3xl transition-left-top duration-250 z-1' }}
          tabs={data}
          isDestroyUnactive
          renderTitle={<RenderTitle />}
          renderContent={<RenderContent Token={userInfo?.Token} />}
        />
      )}
    </div>
  );
}

export default observer(Deposit);
